const router = require('koa-router')();
const submitFeed = require('../../app/mws/feeds/SubmitFeed');
const getFeedSubmissionResult = require('../../app/mws/feeds/GetFeedSubmissionResult');
const obj2excel = require('../../app/util/obj2excel');
const throttle = require('../../app/util/throttle');

router.prefix('/api/v1/feeds/inventory');

router.get('/', function (ctx, next) {
  ctx.body = 'this is a feedsSubmissionInventory response!'
});

/***********************
 *  feed inventory api (excel feeding)
 ************************/
router.post('/submission/:marketplaceid', async (ctx, next) => {
  let sellerId = ctx.headers.sellerid;
  let mwsAuthToken = ctx.headers.mwsauthtoken;

  let marketplaceid = ctx.params.marketplaceid;
  let feedType = "_POST_FLAT_FILE_INVLOADER_DATA_"; // "_POST_INVENTORY_AVAILABILITY_DATA_";  // ref: http://docs.developer.amazonservices.com/en_US/feeds/Feeds_FeedType.html

  let inventory = ctx.request.body;
  const template_name = "priceinventory";

  const xlsx_buffer = await obj2excel.obj2excel(template_name, inventory, 1);
  try {
    let json = await throttle.submitFeedQueue.append(submitFeed.submitFeed, sellerId, mwsAuthToken, feedType, xlsx_buffer, [marketplaceid]);
    // let json = await submitFeed.submitFeed();
    ctx.response.status = 200;
    ctx.response.body = {
      data: json,
    };
  } catch (error) {
    ctx.response.status = 500;
    ctx.response.body = {
      data: error,
    };
  }
});

/***********************
 *  callback of feed product api
 ************************/
router.get('/submission/callback/:submissionid/', async (ctx, next) =>{
  // You exceeded your quota of 60.0 requests per 1 hour for operation Feeds/2009-01-01/GetFeedSubmissionResult.  Your quota will reset on Sun Dec 06 14:09:00 UTC 2020
  let sellerId = ctx.headers.sellerid;
  let mwsAuthToken = ctx.headers.mwsauthtoken;

  let submissionid = ctx.params.submissionid;

  try {
    // let json = await getFeedSubmissionResult.getFeedSubmissionResult(sellerId, mwsAuthToken, submissionid);
    let json = await throttle.getFeedSubmissionResultQueue.append(getFeedSubmissionResult.getFeedSubmissionResult, sellerId, mwsAuthToken, submissionid);
    console.log(json);
    console.log(new Date());

    ctx.response.status = 200;
    ctx.response.body = {
      data: json,
    };
  } catch (error) {
    ctx.response.status = 500;
    ctx.response.body = {
      data: error,
    };
  }
});

module.exports = router;